package com.heima.admin.gateway.filter;

import com.heima.common.dtos.Payload;
import com.heima.common.util.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author Fuqiang
 * @since :2023-03-24
 */
@Slf4j
@Component
public class AuthFilter implements GlobalFilter {
    private static final String LOGIN_URI = "/login/in";

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        // 判断是否为登录请求,如果是 放行
        String uri = request.getURI().getPath();
        if (uri.contains(LOGIN_URI)) {
            return chain.filter(exchange);
        }
        // 如果不是登录请求, 判断是否有Token, 如果没有Token 则直接响应401
        String token = request.getHeaders().getFirst("token");
        try {
            if (StringUtils.isBlank(token)) {
                return this.unauthorizedResponse(response);
            }
            // 如果有Token, 判断Token是否有效; 若Token有效, 将userId放入请求头中并放行
            Payload payload = JwtUtils.getInfoFromToken(token);
            Integer userId = payload.getUserId();
            if (userId != null && userId > 0) {
                request.mutate().header("userId", String.valueOf(userId));
                return chain.filter(exchange);
            }
        } catch (Exception e) {
            log.error("Token校验异常 异常信息: {}, uri: {}, Token: {}", ExceptionUtils.getStackTrace(e), uri, token);
            return this.unauthorizedResponse(response);
        }
        // 如果Token无效, 则直接响应401
        return this.unauthorizedResponse(response);
    }

    /**
     * 构建 未授权响应的方法
     *
     * @param response
     * @return
     */
    private Mono<Void> unauthorizedResponse(ServerHttpResponse response) {
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        return response.setComplete();
    }
}
